package com.wwu.admin.webinit;

import com.wwu.common.constant.CommConst;
import com.wwu.common.web.ResultPage;
import com.wwu.system.entity.SysQuartz;
import com.wwu.system.service.ISysQuartzService;
import com.wwu.system.vo.QueryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 实现CommandLineRunner接口，项目启动后初始化定时任务
 * CommandLineRunner中的Order表示在项目启动时预先加载的类
 * @author 一蓑烟雨
 * @version 1.0.0
 * @date 2023-07-12 17:45
 */
@Slf4j
@Component
@Order(2)
public class QuartzInitialize implements CommandLineRunner {
    /** 注入定时任务接口服务*/
    @Resource
    private ISysQuartzService sysQuartzService;
    /** 注入运行环境 */
    @Value("${spring.profiles.active}")
    private String profiles;

    /**
     * 重写CommandLineRunner接口的run方法
     * @param args 启动参数
     * @author 一蓑烟雨
     * @date 2023/7/12 17:47
     */
    @Override
    public void run(String... args) throws Exception {
        //开发环境不加载定时任务
        if (CommConst.PROFILES_ACTIVE_DEV.equals(profiles)) {
            return;
        }
        //获取启动状态的的任务列表
        ResultPage<SysQuartz> quartzListPage = sysQuartzService.getQuartzListPage(1,5000,new SysQuartz().setQuartzStatus(0),new QueryVO());
        if(!ObjectUtils.isEmpty(quartzListPage.getData())){
            for (SysQuartz sysQuartz: quartzListPage.getData()) {
                //删除任务调度
                sysQuartzService.deleteQuartzScheduler(sysQuartz);
                //添加任务调度
                sysQuartzService.addQuartzScheduler(sysQuartz);
            }
            log.info("--------------------系统定时任务加载成功,共{}条--------------------",quartzListPage.getData().size());
        }else {
            log.info("--------------------系统定时任务加载成功,共{}条--------------------",0);
        }
    }
}
